//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import { GitExtraInfo, NodeData } from '../types';
import LocalNodeWrap from '../LocalNodeWrap';
import { Button, Space } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import type { GitCodeRepo } from "@/api/gitcode/repo";
import { open as shell_open } from '@tauri-apps/api/shell';
import { get_type_name,get_source, type UserDataSourceInfo, type GitSourceInfo } from '@/api/user_dataview';
import { get_repo } from "@/api/gitcode/repo";


const GitCodeBasicInfoNode = (props: NodeProps<NodeData>) => {
    const [repoInfo, setRepoInfo] = useState<GitCodeRepo | null>(null);
    const [dataSource, setDataSource] = useState<UserDataSourceInfo | undefined>(undefined);

    const loadDataSource = async () => {
        const res = await get_source(props.data.dataSourceId ?? "");
        setDataSource(res);
    };

    const getSourceTypeName = () => {
        if (dataSource == undefined) {
            return "";
        }
        return get_type_name(dataSource.source_type);
    };

    const loadRepoInfo = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as GitSourceInfo;
        const extraInfo = props.data.extraInfo as GitExtraInfo;
        const res = await get_repo(sourceInfo.accessToken, extraInfo.ownerName, extraInfo.repoName);
        setRepoInfo(res);
    };


    useEffect(() => {
        loadDataSource();
    }, []);

    useEffect(()=>{
        if(dataSource != undefined){
            loadRepoInfo();
        }
    },[dataSource]);

    return (
        <LocalNodeWrap title={
            <Space>
                <span>{getSourceTypeName()}</span>
                <span>基本信息</span>
                {repoInfo != null && (
                    <a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        console.log(repoInfo);
                        shell_open(repoInfo.http_url_to_repo);
                    }}>{repoInfo.full_name}</a>
                )}
            </Space>
        } nodeData={props} extraButtonList={[
            <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                loadRepoInfo();
            }} title='刷新' />
        ]} canChangeBgColor/>
    );
};

export default GitCodeBasicInfoNode;